package com.wangshb.upms.core.common;

import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class BeanMapper {

    private static Logger logger = LoggerFactory.getLogger(BeanMapper.class);

    public static <T> T map(Object src, Class<T> cls) {

        if (src == null) {
            return null;
        }

        T obj = null;
        try {
            obj = cls.newInstance();
            BeanUtils.copyProperties(src, obj);
        } catch (InstantiationException e) {
            logger.error("类型转换失败", e);
        } catch (IllegalAccessException e) {
            logger.error("类型转换失败", e);
        }
        return obj;
    }

    public static <T> List<Object> mapAsList(List<?> src, Class<T> cls) {

        if (src == null) {
            return Collections.emptyList();
        }

        List<Object> list = new ArrayList<>(src.size());
        src.stream().forEach(value -> list.add(map(value, cls)));
        return list == null ? Collections.emptyList() : list;
    }
}
